package com.easycarebn.main.fragment;

import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.ProgressBar;

import com.easycarebn.main.adapter.MessageAdapter;
import com.easycarebn.main.utils.IResult;
import com.easycarebn.main.utils.Utils;
import com.easycarebn.request.controller.ServerController;
import com.easycarebn.request.data.DataItemResponse;
import com.easycarebn.request.data.NotificationItem;
import com.easycarebn.request.data.NotificationListResponse;
import com.easycarebn.request.data.UserResponse;
import com.easycarebn.service.request.OnRequest;
import com.timbacsi.main.R;

public class FragmentMessage extends Fragment {

    private View mView;
    public static FragmentMessage fragment = null;
    private IResult callIResult;
    private static String mTitle;
    MessageAdapter adapter;
    List<NotificationItem> mListItemNews;
    ListView mListmessage;
    private NotificationItem mNotifiSelected = null;
    private int mPositionSelected;
    private LinearLayout lineTitle;
    private ProgressBar loadding;
    private int mPage = 0;
    private int mLastPage = 0;
    private View mFooter;
    private String mToken = null;

    public static FragmentMessage newInstance(String title) {
        // if (fragment == null)
        fragment = new FragmentMessage();
        mTitle = title;
        return fragment;
    }

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        if (activity instanceof IResult) {
            callIResult = (IResult) activity;
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        mView = inflater.inflate(R.layout.fragment_listview, null);
        Utils.setTitlePage(mView, mTitle);

        return mView;
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        lineTitle = (LinearLayout) mView.findViewById(R.id.lineTitle);
        lineTitle.setVisibility(View.GONE);
        mListmessage = (ListView) mView.findViewById(R.id.listmessage);
        loadding = (ProgressBar) mView.findViewById(R.id.loadding);
        callIResult.onDisplay(Utils.TASK_CHILD, "");
        
        mFooter = getLayoutInflater(savedInstanceState).inflate(R.layout.load_more, null);
        mListmessage.addFooterView(mFooter);
        
        mListItemNews = new ArrayList<NotificationItem>();
        UserResponse user = Utils.getUserLogin(getActivity());
        if (user != null) {
            mToken = user.getToken();
        } else {
            mToken = null;
            Utils.onShowMessageNull(getActivity(), mView, getResources().getString(R.string.vui_long_dang_nhap));
            return;

        }
        adapter = new MessageAdapter(getActivity(), mListItemNews, new IResult() {

            @Override
            public void onDisplay(int arg1, String arg2) {
                mPositionSelected = Integer.parseInt(arg2);
                mNotifiSelected = mListItemNews.get(mPositionSelected);
                if (arg1 == Utils.REMOVE_SMS) {
                    removeSms();
                } else {
                    mListItemNews.get(mPositionSelected).setStatus(1);
                    adapter.notifyDataSetChanged();
                    Bundle data = new Bundle();
                    data.putString(Utils.KEY_ID, mListItemNews.get(mPositionSelected).getId()+"");
                    Utils.intentToDetailt(getActivity(), Utils.NOTIFICATION_DETAILT, data);

                }
            }
        });
        mListmessage.setAdapter(adapter);
        requestLoadMessage();
        
        Button btnLoadmore = (Button) mFooter.findViewById(R.id.btnLoadMore);
        btnLoadmore.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
            	requestLoadMessage();
            }
        });
        mListItemNews.clear();
        mPage = 0;
        mLastPage = 0;
    }

    public void removeSms() {
        Utils.showDialogConfirm(getActivity(), getResources().getString(R.string.xoa_message_des), new IResult() {

            @Override
            public void onDisplay(int arg1, String arg2) {
                if (arg1 == Activity.RESULT_OK) {
                    callAPIRemove();
                }
            }
        });
    }

    public void callAPIRemove() {
        loadding.setVisibility(View.VISIBLE);
        Utils.disableEnableControls(false, (ViewGroup) mView);

        ServerController.getInstance(getActivity()).requestNotificationDelete(mToken, mNotifiSelected.getId(),
                new OnRequest<DataItemResponse>() {

                    @Override
                    public void onSuccess(DataItemResponse data) {
                        loadding.setVisibility(View.GONE);
                        Utils.disableEnableControls(true, (ViewGroup) mView);
                        if (data.getCode() == 200) {
                            adapter.removeItem(mPositionSelected);
                        }
                    }

                    @Override
                    public void onError(int errorCode, String message) {
                        loadding.setVisibility(View.GONE);
                        Utils.disableEnableControls(true, (ViewGroup) mView);
                    }
                });
    }

    public NotificationItem getNotificationItem() {
        return mNotifiSelected;
    }

    private void requestLoadMessage() {
        loadding.setVisibility(View.VISIBLE);
        ServerController.getInstance(getActivity()).requestNotificationList(mToken,mPage+1, new OnRequest<NotificationListResponse>() {

            @Override
            public void onSuccess(NotificationListResponse data) {
                loadding.setVisibility(View.GONE);
                mPage = data.getPaging().getCurrentPage();
                mLastPage = data.getPaging().getLastPage();
                if (mLastPage > mPage) {
                    mFooter.setVisibility(View.VISIBLE);
                } else {
                    mListmessage.removeFooterView(mFooter);
                }
                
                if (data.getNotificationList().size() == 0) {
                    Utils.onShowMessageNull(
                            getActivity(),
                            mView,
                            String.format(getResources().getString(R.string.khong_co_du_lieu),
                                    getResources().getString(R.string.gui_tin)));

                    return;
                }
                lineTitle.setVisibility(View.VISIBLE);
                mListItemNews.addAll(data.getNotificationList());
                adapter.notifyDataSetChanged();
            }

            @Override
            public void onError(int errorCode, String message) {
                loadding.setVisibility(View.GONE);
                lineTitle.setVisibility(View.GONE);
                if (errorCode == 0) {
                    Utils.onResumeRequest(getActivity(), mView, new IResult() {
                        @Override
                        public void onDisplay(int arg1, String arg2) {
                            requestLoadMessage();
                        }
                    });
                }
            }
        });
    }
}
